package repository

import (
	"fitness/go-admin/internal/model"

	"gorm.io/gorm"
)

// SensitiveWordRepository 敏感词数据访问层
type SensitiveWordRepository struct {
	db *gorm.DB
}

// NewSensitiveWordRepository 创建敏感词仓库
func NewSensitiveWordRepository(db *gorm.DB) *SensitiveWordRepository {
	return &SensitiveWordRepository{db: db}
}

// Create 创建敏感词
func (r *SensitiveWordRepository) Create(word *model.SensitiveWord) error {
	return r.db.Create(word).Error
}

// GetByID 根据ID获取敏感词
func (r *SensitiveWordRepository) GetByID(id uint) (*model.SensitiveWord, error) {
	var word model.SensitiveWord
	err := r.db.First(&word, id).Error
	if err != nil {
		return nil, err
	}
	return &word, nil
}

// GetByWord 根据词获取敏感词
func (r *SensitiveWordRepository) GetByWord(word string) (*model.SensitiveWord, error) {
	var sensitiveWord model.SensitiveWord
	err := r.db.Where("word = ?", word).First(&sensitiveWord).Error
	if err != nil {
		return nil, err
	}
	return &sensitiveWord, nil
}

// GetAllEnabled 获取所有启用的敏感词
func (r *SensitiveWordRepository) GetAllEnabled() ([]model.SensitiveWord, error) {
	var words []model.SensitiveWord
	err := r.db.Where("is_enabled = ?", true).Find(&words).Error
	return words, err
}

// GetList 获取敏感词列表
func (r *SensitiveWordRepository) GetList(req *model.SensitiveWordListReq) ([]model.SensitiveWord, int64, error) {
	var words []model.SensitiveWord
	var total int64

	query := r.db.Model(&model.SensitiveWord{})

	// 分类筛选
	if req.Category != "" {
		query = query.Where("category = ?", req.Category)
	}

	// 级别筛选
	if req.Level != "" {
		query = query.Where("level = ?", req.Level)
	}

	// 启用状态筛选
	if req.IsEnabled != nil {
		query = query.Where("is_enabled = ?", *req.IsEnabled)
	}

	// 关键词搜索
	if req.Keyword != "" {
		query = query.Where("word LIKE ?", "%"+req.Keyword+"%")
	}

	// 计数
	query.Count(&total)

	// 分页
	offset := (req.Page - 1) * req.PageSize
	err := query.Order("created_at DESC").
		Offset(offset).
		Limit(req.PageSize).
		Find(&words).Error

	return words, total, err
}

// Update 更新敏感词
func (r *SensitiveWordRepository) Update(id uint, updates map[string]interface{}) error {
	return r.db.Model(&model.SensitiveWord{}).
		Where("id = ?", id).
		Updates(updates).Error
}

// Delete 删除敏感词
func (r *SensitiveWordRepository) Delete(id uint) error {
	return r.db.Delete(&model.SensitiveWord{}, id).Error
}

// BatchCreate 批量创建敏感词
func (r *SensitiveWordRepository) BatchCreate(words []model.SensitiveWord) error {
	return r.db.Create(&words).Error
}

// CheckExists 检查敏感词是否存在
func (r *SensitiveWordRepository) CheckExists(word string) (bool, error) {
	var count int64
	err := r.db.Model(&model.SensitiveWord{}).Where("word = ?", word).Count(&count).Error
	return count > 0, err
}

